/**
 * 帮助文档加载
 */
 import React, { Component } from 'react';
import { Homepage } from '../App';
import { mdRender } from '../common/Common';

 import TDom from "../common/TDom";
 
 class TClassesLoader extends Component{
  constructor(props){
    super(props);

    this.state={   
      classInfo : props.ClassInfo,

      classCatalog  : [],
      classAttachments : [],
      classHtmlLink : '',
    }

    this.home             = this.home.bind(this);
    this.cancelArrowEvent = this.cancelArrowEvent.bind(this);
    this.handleKeyDown    = this.handleKeyDown.bind(this);
    this.handleMenuClick  = this.handleMenuClick.bind(this);

    this.viewHistroy  = [];
    this.divContent  = React.createRef();
  }
 
  componentDidMount(){
    // 加载课程
    this.loadClass();

    document.onkeydown=this.cancelArrowEvent;
    window.addEventListener('keydown', this.handleKeyDown, false);
  }
 
  // 加载课程目录
  loadClass(){
    const url = `/${Homepage}/${this.state.classInfo.classUrl}/index.json`;
    console.log(`课程地址：${url}`)
    TDom.getDataFromUrl(url,(json)=>{
      let catalog = [];

      for(let key in json){
        var tmp = json[key];
        tmp.title = key;
        catalog.push(tmp);
      }

      this.setState({
        classCatalog  : catalog,
        selectedIndex : 0,
      })

      if(catalog.length > 0){
        this.updateManual(catalog[0]);
      }
    })
  }
 
  componentWillUnmount(){
    document.onkeydown = '';
    window.removeEventListener('keydown', this.handleKeyDown, false);
  }
 
   
  cancelArrowEvent(event){
    if(event.key === 'ArrowDown' || event.key === 'ArrowUp'){
      return false;
    }
  }
 
  handleKeyDown(event){
    if(event.key === 'ArrowDown'){
      let selected = this.state.selectedIndex;
      if(selected < this.state.manualMenu.length - 1){
        selected += 1;
        this.setState({
          selectedIndex : selected
        })
      }
    }
    else if(event.key === 'ArrowUp'){
      let selected = this.state.selectedIndex;
      if(selected > 0){
        selected -= 1;

        this.setState({
          selectedIndex : selected
        })
      }
    }
    else if( event.key === 'Enter'){
      this.updateManual();
    }
  }

  handleMenuClick(event){
    this.updateManual(this.state.classCatalog[event.target.id]); 

    this.setState({
      selectedIndex : event.target.id
    })
  }
 
  updateManual(chapter){
    if(chapter === undefined) chapter = this.state.classCatalog[this.state.selectedIndex];

    // 加载章节内容
  
    // 加载ReadMe文件并渲染
    TDom.getDataFromUrl(`/${Homepage}/${this.state.classInfo.classUrl}/${chapter.ReadMe}`,
      (md)=>{
        this.processMD(chapter, md)
      }
    );

    // 设置外联地址
    var attachments = [];
    for(let key in chapter){
      if(key === 'assets' || key === 'title') continue;
      attachments.push({id:key, url:chapter[key]});
    }
    this.setState({
      classHtmlLink    : chapter.html,
      classAttachments : attachments,
    })
  }

  // 处理md文件并渲染
  processMD(chapter, md){

    // 标签中src相对路径为绝对路径
    md = md.replace(/src\s*=\s*.\//ig, `src = /${Homepage}/${this.state.classInfo.classUrl}/${chapter.assets}/`);
    md = md.replace(/src\s*="\s*.\//ig, `src = "/${Homepage}/${this.state.classInfo.classUrl}/${chapter.assets}/`);
    // 修复$$\begin问题
    md = md.replace(/\$\$/ig,"\r\n$$\r\n");

    mdRender(md, this.divContent.current);
  }

  home(){
    this.props.home();
  }
 
  loadManual(url){
  if(this.props.BaseUrl){
    url = `${this.props.BaseUrl}/${url}`;
  }

  TDom.getDataFromUrl(url, (md)=>{
    mdRender(md, this.divContent.current);
  })
  }
 
 
  _renderMenu(){
    const menu = this.state.classCatalog;
    const selected   = parseInt(this.state.selectedIndex);

    return menu.map((item, key)=>
      <button className={key===selected?'menu-selected':'menu'} 
        key={key} 
        id={key}
        onClick={this.handleMenuClick}>
      {item.title}</button>
    );
  }
 
 
  render(){
    return (
      <div className='book'>
        <div className='slider'>
          <button onClick={this.home}>返回</button>
          <b>{this.state.classInfo.className}</b>
          {this._renderMenu()}
        </div>
        <div className='div-flex-column'>
          <div >
            下载附件：
            {
              this.state.classAttachments.map((item, key)=>
              <a style={{margin:"5px"}} key={key} href={`/${Homepage}/${this.state.classInfo.classUrl}/${item.url}`}>
                {item.id}
              </a>)
            }
            {/* <a href={`/${Homepage}/${this.state.classInfo.classUrl}/${this.state.classHtmlLink}`}>{this.state.classHtmlLink}</a> */}
            </div>
          <div ref={this.divContent}></div>
        </div>
      </div>
    );
  }
}
 
 export default TClassesLoader;